﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Text;
using IDotNet;
using IDotNet.MapLibs.Model;
using NLog;

namespace IDotNet.MapLibs
{
    public class MapLibHelper
    {
        public static ILogger Log
        {
            get
            {
                return LogManager.GetLogger("MapLibs");
            }
        }
        public static T GetHttpResult<T>(string url, NameValueCollection parms)
        {
            var res = GetHttpResult(url, parms);
            if (res.IsNullOrWhiteSpace())
            {
                throw new MapLibException("远程服务器返回值为空！") { };
            }
            return res.ToDeserializeJson<T>();
        }

        public static string GetHttpResult(string url, NameValueCollection parms, string method = "post")
        {
            using (var webClent = new WebClient())
            {
                webClent.Headers.Add("User-Agent",
                    " Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");
                if (Log.IsDebugEnabled)
                {
                    Log.Debug("url:{0}\r\nparams:{1}".FormatWith(url, parms.ToQueryString()));
                }
                byte[] data;
                if (string.Equals("get", method, StringComparison.OrdinalIgnoreCase))
                {
                    data =
                        webClent.DownloadData(url + (url.Contains("?") ? "&" : "?") +
                                              parms.ToQueryString((ns, key) => ns[key].UrlEncode()));
                }
                else
                {
                    data = webClent.UploadValues(url, method, parms);
                }
                var str = Encoding.UTF8.GetString(data);
                Log.Debug(str);
                return str;
            }
        }

        public static string GetHttpResult(string url, Dictionary<string, string> parms)
        {
            string datas = parms.ToQueryString();
            var res = HttpHelper.httpPost(url, datas, "application/x-www-form-urlencoded", 10000, Encoding.UTF8);
            return res;
        }

        public static string GetAppConfigValue(string key)
        {
            return WebConfigHelper.GetAppSettingValue(key);
        }

        public static T ToDeserialize<T>(string str, bool isJson = true) where T : class
        {
            return isJson ? str.ToDeserializeJson<T>() : str.ToDeserializeXml<T>();
        }
    }
}
